<?php
/**
 * 
 *
 * @category   Application_Extensions
 * @package    Recorder
 * @copyright  Copyright 2006-2010 Idragonsolution Developments
 * @license    http://idragonsolution.com/
 * @version    $Id: Bootstrap.php 9747 2012-07-26 02:08:08Z Thien $
 * @author     Thien
 */
class Recorder_Api_Core extends Core_Api_Abstract
{
    // handle recorder upload
  public function createRecorder($file, $params = array())
  {
    if( is_array($file) ) {
      if( !is_uploaded_file($file['tmp_name']) ) {
        throw new Exception('Invalid upload or file too large');
      }
      $filename = $file['name'];
    } else if( is_string($file) ) {
      $filename = $file;
    } else {
      throw new Exception('Invalid upload or file too large');
    }

    // Check file extension
    if( !preg_match('/\.(mp3|m4a|aac|mp4)$/iu', $filename) ) {
      throw new Exception('Invalid file type');
    }

    // upload to storage system
    $params = array_merge(array(
      'type' => 'recorder',
      'name' => $filename,
      'parent_type' => 'recorder',
      'parent_id' => Engine_Api::_()->user()->getViewer()->getIdentity(),
      'user_id' => Engine_Api::_()->user()->getViewer()->getIdentity(),
      'extension' => substr($filename, strrpos($filename, '.') + 1),
    ), $params);

    $recoder = Engine_Api::_()->storage()->create($file, $params);

    return $recoder;
  }
  
  public function getSelect($params = array())
  {
    $table = Engine_Api::_()->getDbtable('recorders','recorder');
    $select = $table->select();
    $select->where('search = ?',1);
    
    if (isset($params['search']) && is_string($params['search'])){
        $select->where('title LIKE ? OR description LIKE ?', '%'.$params['search'].'%');
    }
    if (isset($params['user_id'])){
        $select->where('owner_id = ?',$params['user_id']);
    }

    return $select;
  }

  public function getPaginator($params = array())
  {
    $paginator = Zend_Paginator::factory($this->getSelect($params));
    if( !empty($params['page']) ) {
      $paginator->setCurrentPageNumber($params['page']);
    }
    if( !empty($params['limit']) ) {
      $paginator->setItemCountPerPage($params['limit']);
    }
    return $paginator;
  }
  
  
  public function deleteRecorder($recorder)
  {

    // delete paint ratings
    Engine_Api::_()->getDbtable('ratings', 'recorder')->delete(array(
      'recorder_id = ?' => $recorder->recorder_id,
    ));

   
    
    // delete activity feed and its comments/likes
    $item = Engine_Api::_()->getItem('recorder', $recorder->recorder_id);
    if ($item) {
      $item->delete();
    }


  }
}